<template>
	<div class="posre borderbox wrapper h100p" :style="{height: mainHeight+'px'}">
			<!-- <div class="w100p"
           style="position: relative; z-index: 2">
        <SelfSwiper :imgUrls="banners"
                    :self_class="'h211'"
                    :isShowMask="true"
                    @swipclick="preview"
                    :isShowDots="false" />
      </div> -->
			
			<!--拼团抢购-->
			<div style="width: 100%;margin-top: 30upx;">
				<div style="width: 100%;display: flex;flex-direction: row;margin-right: 20upx;">
					<div style="width: 4upx;height: 40upx;background-color: #20B31C;"></div>
					<!--小标-->
					<text style="text-align: left;font-size: 30upx;font-weight: 600;margin-left: 20upx;">拼团抢购</text>
					
				</div>
				<div>
						
							<div style="display: flex ;flex-direction: row;width: 100%;">
								<div style="display: flex;flex-direction: column;">
									<image src="http://yueang2.oss-cn-qingdao.aliyuncs.com/wm-img/banner.png" style="width: 265upx;height: 230upx;margin-left: 20upx;margin-top: 20upx;"></image>
									<div style="background-color:red;height: 35upx;line-height: 35upx;text-align: center;margin-left: 20upx;align-items: center;">
										<text style="font-size: 20upx;color: white;line-height: 35upx;">距离结束 {{remaining}}</text>
									</div>
								</div>
								<div style="display: flex;flex-direction: column;margin-top: 45upx;margin-left: 20upx;">
									<text style="font-size: 28upx;color: #848484;">卫龙辣条卫龙大卫龙</text>
									
									<div style="display: flex;flex-direction: row;margin-top: 130upx;">
										<text style="font-size: 28upx;color: red;">￥100</text>
										<text style="font-size: 25upx;color: #B9B9B9;">￥120</text>
										<div style="width: 100upx;height: 30upx;line-height: 30upx;border: 1px solid red;color: red;font-size: 25upx;margin-left: 120upx;text-align: center;border-radius: 10upx;">立即跟团</div>
									</div>
								</div>
							</div>
				</div>
			</div>
			<div>
				<!--原来的获取商品列表-->
				<!-- <div class="disflex jsbet bgf5f6 pl15 pr16 wrap pb23"
             v-if="prod_lists.length">
          <getPhoneNumberGoods v-for="(v,k) in prod_lists"
                               :key="k"
                               @next="toProdDetail"
                               @loginGuide="loginGuide"
                               :goodInfo="v">
          </getPhoneNumberGoods>
          <LoginIntercept @loginSuccess="loginInterceptSuccess"
                          class="login-intercept" />
        </div> -->
				<!--lists end-->

			</div>

			<!--右边悬浮框-->
			<!--    <div class="posfix right11 add_white bottom10 w40 h40 bg_line_blue bradius50p textc lh40" @click="right_float_show = !right_float_show">-->

			<!--    </div>-->

			<!--bottom-->
			<div class="textc lh42 fs12 ca8 bgf5f6" v-if="nodata && prod_lists.length">- 到底了，看看其他的吧 -</div>
		</scroll-view>
		<!-- <div class="index_float_right trans2 overhidden">
      <RightFloat :isShow="isShow"  @clickRightRowEvent="clickRightRowEvent"></RightFloat>
      <div :class="{fadeInRight: !isShow, fadeOutRight: isShow}" style="width: 40rpx;right: 0;border-top-left-radius: 10rpx;border-bottom-left-radius: 10rpx"  class="animated posfix fs10  ca8 textc floats trans2 bottom30  shadow_gray bgfff pb15"> 
        <div class="pt16" @click="clickRightRowEvent">
          <img src="https://yueang2.oss-cn-qingdao.aliyuncs.com/yimai_photos/user/right_row.png" alt="" style="width: 30rpx;transform: rotate(180deg);height: 30rpx;">
        </div>
      </div>
    </div> -->

		<FloatButtons class="index_float_right trans2 overhidden" :isShowTalk="isShowTalk" :avatarUrl="targetAvatarUrl" @talk="talk"
		 @loginGuide="loginGuide"></FloatButtons>
	</div>
</template>

<script>
	import RightFloat from '@/components/rightFloat' // 订单项
	import getPhoneNumberGoods from '@/components/getPhoneNumberGoods' //
	import AuthenticationTag from '@/components/AuthenticationTag' //
	import WXAJAX from '../../utils/request'
	import NoData from '@/components/noData'
	import utils from '@/utils'
	import SelfSwiper from '@/components/swiper' //
	import {
		mapState
	} from "vuex";
	import FloatButtons from "@/components/FloatButtons.vue"
	import NavBarByUser from '@/components/NavBarByUser.vue';
	import HandleLogin from "@/utils/handleLogin";
	import LoginIntercept from "@/components/LoginIntercept";
	import {
		addShareRecord
	} from '@/utils/behavior';

	export default {
		name: '',
		components: {
			RightFloat,
			NoData,
			getPhoneNumberGoods,
			SelfSwiper,
			AuthenticationTag,
			FloatButtons,
			NavBarByUser,
			LoginIntercept
		},
		data() {
			return {
				remaining: '', //显示剩余时间
				remainingd: '', //数据返回时间秒

				//分类
				goodstypeData: [{
						typename: "分类",
						typeimg: "http://yueang2.oss-cn-qingdao.aliyuncs.com/wm-img/banner.png"
					},
					{
						typename: "分类",
						typeimg: "http://yueang2.oss-cn-qingdao.aliyuncs.com/wm-img/banner.png"
					},
					{
						typename: "分类",
						typeimg: "http://yueang2.oss-cn-qingdao.aliyuncs.com/wm-img/banner.png"
					},
					{
						typename: "分类",
						typeimg: "http://yueang2.oss-cn-qingdao.aliyuncs.com/wm-img/banner.png"
					},
					{
						typename: "分类",
						typeimg: "http://yueang2.oss-cn-qingdao.aliyuncs.com/wm-img/banner.png"
					},
					{
						typename: "分类",
						typeimg: "http://yueang2.oss-cn-qingdao.aliyuncs.com/wm-img/banner.png"
					},
					{
						typename: "分类",
						typeimg: "http://yueang2.oss-cn-qingdao.aliyuncs.com/wm-img/banner.png"
					},
					{
						typename: "全部分类",
						typeimg: "http://yueang2.oss-cn-qingdao.aliyuncs.com/wm-img/banner.png"
					}
				],
				canClickStar: true, // 是否可以点击star按钮
				menu: [{
					name: '全部',
					goodstypeId: '-10'
				}],
				menu_id: '-10',
				prod_lists: [],
				nodata: false, //是否已经没有数据
				COMPANYID: 0,
				company_msg: {
					admin_logo: '',
					company_logo: '',
					company_name: ''
				},
				currentPage: 1,
				isCollect: false, //是否收藏
				collectionId: 0,
				page: 1,
				isLoading: false, //是否在加载
				right_float_show: false, //右边悬浮框
				nav_top: false,
				banners: ['http://yueang2.oss-cn-qingdao.aliyuncs.com/product-index/20190418160834.png'],
				isShow: true,

				avatarUrl: '', //用户的头像地址,
				isLogin: HandleLogin.returnIsLogin() || false, //是否已经登录
				isShowTalk: true, //是否显示右边侧边栏的聊一聊
				isShowLoginGuide: true, //是否显示登录引导页,
				targetAvatarUrl: '', //当前目标的人物头像
				scrollContentHeight: 0, //中间滚动区域的高度
				mainHeight: 0 //整体高度
			}
		},
		onShow() {
			//获取当前的公司
			let lastCompanyid = this.COMPANYID;
			this.COMPANYID = wx.getStorageSync('COMPANYID') || 0;
			//this.getProds();

			if (lastCompanyid != this.COMPANYID || !this.COMPANYID) {
				this.prod_lists = [];
				this.page = 1;
				this.getcompany();
				this.menu_tap('-10');
				this.getAd();
			}
			this.isLogin = HandleLogin.returnIsLogin() || false;
			this.avatarUrl = wx.getStorageSync('avatarUrl') || '';

			//this.getMeuns();
		},
		async mounted() {
			let a = await utils.systemIfo();
			let navHeight = getApp().globalData.navHeight;
			this.mainHeight = a.windowHeight;
			this.scrollContentHeight = a.windowHeight - navHeight;
		},
		computed: {
			...mapState({
				currentCompany: state => state.currentCompany
			})
		},
		watch: {
			currentCompany: {
				deep: true,
				immediate: true,
				handler(newVal) {
					if (newVal) {
						if (newVal.userId === wx.getStorageSync('userId')) {
							this.isShowTalk = false;
						} else {
							this.isShowTalk = true;
							this.targetAvatarUrl = newVal.logo;
						}
					}
				}
			}
		},
		async onShareAppMessage(e) {
			let COMPANYID = wx.getStorageSync('COMPANYID') || 0;
			let CARDID = wx.getStorageSync('CARDID') || 0;

			this.addGoodsForwardRecord(CARDID);
			let shareId = await addShareRecord(COMPANYID, 2);

			return {
				path: '/pages/Product/main?cardId=' + CARDID + '&companyId=' + COMPANYID + '&goType=1&shareId=' + shareId,
				success(e) {
					wx.showShareMenu({
						withShareTicket: true
					})
				},
				fail(e) {
					console.log('失败分享名片--- ', e);
				}
			}
		},
		onPageScroll(e) {
			// if (e.scrollTop > 200) {
			//   wx.setNavigationBarColor({
			//     frontColor: '#000000',
			//     backgroundColor: '#ffffff',
			//     animation: {
			//       duration: 200,
			//       timingFunc: 'easeIn'
			//     }
			//   })
			// } else {
			//   wx.setNavigationBarColor({
			//     frontColor: '#ffffff',
			//     backgroundColor: '#ffffff',
			//     animation: {
			//       duration: 200,
			//       timingFunc: 'easeIn'
			//     }
			//   });
			// }
		},
		async onPullDownRefresh() {
			// to doing..
			// 停止下拉刷新
			wx.showNavigationBarLoading();
			this.page = 1;
			this.prod_lists = [];
			this.nodata = false;
			this.isLoading = false;
			//this.getProds();
			//this.getMeuns();
			this.getcompany();
			this.getAd();
			this.menu_tap(this.menu_id || '-10');
			wx.showLoading();
			wx.stopPullDownRefresh();
			setTimeout(function() {
				wx.hideLoading();
				wx.hideNavigationBarLoading();
			}, 300)
		},
		methods: {
			moreshop(){
				uni.navigateTo({
					url:""
				})
			},
			morekill(){
				uni.navigateTo({
					url:"../goodskill/goodskill"
				})
			},
			//获取列表信息
			getmsglist: function() {
				var _self = this;
				_self.remainingd = 0; //倒计时时间
				_self.jishiqi(); //执行一次倒计时，因为进入页面有等待

				setInterval(function() {
					_self.jishiqi();
				}, 1000)

				uni.hideLoading(); //关闭加载
			},
			//倒计时计时器
			jishiqi: function() {
				var dj = this.remainingd;
				if (dj <= 0) {
					this.remaining = "已过期";
				} else {
					var ddf = this.djs(dj); //格式化过后的时间
					this.remaining = ddf;
					//当前时间减去时间
					dj = dj - 1;
					this.remainingd = dj;
				}

			},
			//得到的秒换算成时分秒
			djs: function(ms) {
				var h = parseInt(ms / (60 * 60));
				var m = parseInt((ms % (60 * 60)) / 60);
				var s = (ms % (60 * 60)) % 60;
				return h + ":" + m + ":" + s;
			},

			//下拉刷新
			scrolltoupper(e) {
				this.page = 1;
				this.prod_lists = [];
				this.nodata = false;
				this.isLoading = false;
				this.getcompany();
				this.getAd();
				this.menu_tap(this.menu_id || '-10');
				wx.showLoading();
			},
			//上拉加载更多
			scrolltolower(e) {
				// this.showCompany = false;
				// wx.showLoading({
				//   title : '加载中...',
				// });
				let v = this;
				v.getProds();
			},
			//隐藏登录引导
			cancelLoginGuide() {
				this.isShowLoginGuide = false;
			},
			//需要登录引导的回调
			loginGuide() {
				this.isShowLoginGuide = true;
			},
			// 其他监听事件登录 成功回调
			loginInterceptSuccess() {
				console.log("登录拦截回调")
				this.avatarUrl = wx.getStorageSync('avatarUrl') || '';
			},
			//聊一聊
			talk() {
				wx.navigateTo({
					url: '../IM/main?userId=' + this.currentCompany.userId +
						'&logo=' + this.currentCompany.logo +
						'&type=2&cardId=' + this.currentCompany.cardId +
						'&name=' + this.currentCompany.name +
						'&wxCode=' + (this.currentCompany.personalWx || "") +
						'&phone=' + this.currentCompany.phone
				});
			},
			//头像登录成功的回调
			loginSuccess(url) {
				this.isLogin = true;
				this.hasCard = wx.getStorageSync('hasCard') || false;
				this.avatarUrl = wx.getStorageSync('avatarUrl') || '';
			},
			loginFailed() {
				this.isShowLoginGuide = true;
			},
			toSearchGoods() {
				console.log('toSearchGoods')
				wx.navigateTo({
					url: '../searchGoods/main?companyId=' + this.COMPANYID
				});
			},
			preview(idx) {
				this.previewImages(this.banners, this.banners[idx])
			},
			clickRightRowEvent() {
				this.isShow = !this.isShow
				console.log('收起浮窗')
			},
			getAd() {
				this.getPlateAds(1).then(res => {
					this.banners = res ? res.map(val => val.photo) : [
						'http://yueang2.oss-cn-qingdao.aliyuncs.com/product-index/20190418160834.png'
					];
				}).catch(() => {
					this.banners = ['http://yueang2.oss-cn-qingdao.aliyuncs.com/product-index/20190418160834.png'];
				});
			},
			getcompany() { //获取公司信息
				let v = this;
				WXAJAX.POST({
					companyId: v.COMPANYID,
				}, '', '/goods/getCompanyInfo/V2').then((data, code) => {
					if (data) {
						v.company_msg = {
							admin_logo: data.userLogo || '',
							company_logo: data.companyLogo || '',
							company_name: data.companyName || '',
						}
						v.company_msg = {
							company_logo: data.companyLogo,
							company_name: data.companyName,
						}
						v.isCollect = data.isCollection == 1;
						if (data.goodstypeModelList) {
							// v.menu_id = data.goodstypeModelList[0].goodstypeId ;
							v.menu = [{
								name: '全部',
								goodstypeId: -10
							}, ...data.goodstypeModelList];
							//获取分类下的产品
						} else {
							v.menu_id = '';
							v.menu = '';
							v.prod_lists = [];
						}
					}
				}).catch((err) => {
					this.company_msg = {};
				})
			},
			getMeuns() { //获取所有的分类
				let v = this;
				wx.showLoading();
				WXAJAX.POST({
					companyId: v.COMPANYID,
				}, '', '/goods/getGoodsType').then((data, code) => {
					// wx.hideLoading();
					if (data) {
						v.company_msg = {
							company_logo: data[0].companyLogo,
							company_name: data[0].companyName,
						}
						v.menu_id = data[0].goodstypeId;
						v.menu = data;
						v.isCollect = data[0].isCollection == 1;
						//获取分类下的产品
						v.menu_tap(v.menu_id);
					}
					wx.hideLoading();
				}).catch((err) => {
					wx.hideLoading();
					v.menu = [];
				})
			},
			checkCollect() { //
				WXAJAX.checkCollect({
					itemType: 3,
					itemId: this.COMPANYID,
				}).then((data) => {
					this.isCollect = data.status;
					this.collectionId = data.collectionId || 0;
				}).catch((err) => {

				})
			},
			getProds() { //获取产品
				let v = this;
				if (v.isLoading) {
					wx.hideLoading();
					return;
				}
				v.isLoading = true;
				WXAJAX.POST({
					goodstypeId: v.menu_id,
					pageNum: v.page,
					companyId: wx.getStorageSync('COMPANYID'),
					cardId: wx.getStorageSync('CARDID'),
				}, '', '/goods/getGoodsList/V2').then((data) => {
					wx.hideLoading();
					if (data) {
						// wx.showToast({
						//   title: '更新成功',
						//   icon: 'success',
						//   duration: 1000
						// })
						data.forEach(function(i, k) {
							if (i.goodPhoto) {
								i.prodLogo = i.goodPhoto.split(',')[0];
							} else {
								i.prodLogo = '';
							}
							if (i.price) {
								i.price /= 100;
								i.price = i.price.toFixed(2);
							} else {
								i.price = '';
							}
						});
						v.prod_lists = [...v.prod_lists, ...data];
						v.page++;
						setTimeout(function() {
							v.isLoading = false;
						}, 500);
					} else {
						// wx.showToast({
						//   title: '没有更多信息',
						//   icon: 'success',
						//   duration: 1000
						// })
						// // v.prod_lists = [] ;
						// setTimeout(function () {
						//   v.nodata = true ;
						//   v.isLoading = false ;
						// },500);
					}
				}).catch((err) => {
					console.log(err);
					v.prod_lists = [];
					wx.hideLoading();
					if (err.code == 204) {
						v.nodata = true;
					}
					setTimeout(function() {
						v.isLoading = false;
					}, 500);
				})
			},
			menu_tap(id) {
				this.menu_id = id || '';
				this.page = 1;
				this.nodata = false;
				this.isLoading = false;
				this.prod_lists = [];
				wx.showLoading();
				this.getProds();
			},
			toProdDetail: utils.throttle(function(id) {
				let prod = this.prod_lists.filter(prod => {
					return prod.goodsId === id
				})[0];
				wx.setStorageSync('prod', prod)
				wx.navigateTo({
					url: '../prodDetail/main?goodId=' + id
				});
			}, 1000),
			collect() { //收藏企业
				// 没有登录，提醒登录
				if (!HandleLogin.returnIsLogin()) {
					this.loginGuide();
					return;
				}

				if (this.canClickStar) {
					this.canClickStar = false
					let _url = '',
						_request = {};
					if (this.isCollect) { //取消收藏
						_url = '/personal/delCollection';
						_request = {
							itemType: 3,
							itemId: this.COMPANYID,
						}
					} else { //添加收藏
						_url = '/personal/addCollection';
						_request = {
							itemType: 3,
							itemId: this.COMPANYID,
						}
					}
					WXAJAX.changeCollect(_request, _url).then((data) => {
						console.log(data);
						if (data) {
							this.isCollect = !this.isCollect;
							wx.showToast({ // 这玩意要不要，跟产品协商一下，感觉体验不好
								title: this.isCollect ? '收藏成功！' : '取消收藏！',
								icon: 'none',
								duration: 2000
							});
						}
						setTimeout(() => { // 防止用户多次点击，具体时间咨询产品
							this.canClickStar = true
						}, 200)
					}).catch((err) => {
						setTimeout(() => {
							this.canClickStar = true
						}, 200)
					});
				}
			}
		},
		onLoad() {
			uni.showLoading(); //数据加载中
			this.getmsglist(); //第一次加载数据
		}
		// onReachBottom() {
		//   this.showCompany = false;
		//   wx.showLoading({
		//     title : '加载中...',
		//   });
		//   let v = this ;
		//   v.getProds();
		// },
	}
</script>

<style>
	.goodstype {
		width: 100%;
		height: 300upx;
	}

	.type {
		width: 25%;
		height: 150upx;
		display: flex;
		flex-direction: column;
		font-size: 25upx;
		text-align: center;
		float: left;

	}

	.type image {
		border-radius: 50%;
		width: 100upx;
		height: 100upx;
		margin-left: 45upx;
		margin-bottom: 10upx;
		margin-top: 20upx;
	}

	.swp swiper-item image {
		width: 100%;
	}

	.company-title {
		margin-top: -60upx;
		position: relative;
		z-index: 3;
	}

	.menu_more {
		right: 32upx;
		top: 0;
		bottom: 0;
		margin: auto;
	}

	.nav {
		height: 90upx;
		width: 100%;
		line-height: 88upx;
		font-size: 28upx;
		white-space: nowrap;
		/* position: sticky;
    top: 0; */
		/*   position: fixed;
       top: 0;
       left: 0;
       z-index: 99;*/
	}

	.nav_top {
		position: sticky;
		background: white;
		/* padding-top: 140upx; */
		/* margin-top: -140upx; */
		top: 0;
		z-index: 100;
	}

	.nav-item {
		/*width: 20%;*/
		display: inline-block;
		text-align: center;
		margin-right: 48upx;
	}

	.nav-item.active {
		border-bottom: 4upx solid #51cdcb;
		color: #51cdcb;
		font-weight: bold;
	}

	.prod_float_right>div {
		bottom: 120upx;
	}
</style>
